package com.example.traning.jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author lei yu
 * @since 2025/04/21
 */
public class DbUtils {

    static Properties properties = new Properties();

    static {
        try {
            InputStream inputStream = DbUtils.class.getClassLoader()
                    .getResourceAsStream("db.properties");
            properties.load(inputStream);

            // 1,注册驱动：⼿动加载字节码⽂件到 JVM 中
            Class.forName(properties.getProperty("driver"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection() throws SQLException {
        // 2,连接数据库：参数1：url、参数2：用户、参数3：密码
        return DriverManager.getConnection(properties.getProperty("url"),
                properties.getProperty("user"), properties.getProperty("password"));
    }

    public static void closeAll(Connection conn, Statement stmt, ResultSet rs) throws Exception {
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
        if (conn != null) {
            conn.close();
        }
    }

    public static void main(String[] args) throws IOException {
        InputStream inputStream = DbUtils.class.getClassLoader()
                .getResourceAsStream("db.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        Object o = properties.get("user");
        System.out.println("o = " + o);
    }
}
